package tt.dz.service.imp.middleware;

import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tt.dz.dao.ext.base.OmsDeviceTypeDao;
import tt.dz.dao.ext.charger.*;
import tt.dz.dao.ext.dic.OmsDicForwardSrvInfoDao;
import tt.dz.dao.ext.system.OmsLoginDao;
import tt.dz.dao.ext.system.OmsOperationSpListDao;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.OmsDeviceType;
import tt.dz.entity.base.OmsFactoryList;
import tt.dz.entity.charger.*;
import tt.dz.entity.dic.OmsDicForwardSrvInfo;
import tt.dz.entity.exception.BizException;
import tt.dz.entity.exception.ChargerNotFoundException;
import tt.dz.entity.exception.FwdServerNotFoundException;
import tt.dz.entity.exception.OmsDaoException;
import tt.dz.entity.system.OmsOperationSpList;
import tt.dz.service.middleware.LoginService;
import tt.dz.service.middleware.SetService;
import tt.dz.service.sys.ChargerService;
import tt.dz.tcp.socket.exception.CreateConnectionFailException;
import tt.dz.tcp.socket.exception.RetryFailException;
import tt.dz.util.OmsCodesConstants;
import tt.dz.util.OmsConstant;
import tt.dz.util.OmsConstant.MsgResponseCodeEnum;
import tt.dz.util.StringUtil;
import tt.dz.util.annotation.SNUtils;

/*响应代码(HEX)
00 00 00	正常	
FF FF FF	系统错误	
FF FF 01	解密错误	
FF 00 01	注册账号错误	
FF 00 02	注册密码错误	
FF 00 03	城市代码不合法	
FF 01 01	注册设备地址重名	
FF 01 02		
FF 02 01	命令执行失败	
 * */
@Service @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class LoginServiceImpl implements LoginService{
	private Log log = LogFactory.getLog(LoginServiceImpl.class);

	@Resource
	OmsChargerDao omsChargerDao;
	@Resource
	OmsLoginDao omsLoginDao;
	@Resource
	OmsDicForwardSrvInfoDao omsDicForwardSrvInfoDao;
	@Resource
	OmsChargerStateAlternateDao omsChargerStateAlternateDao;
	@Resource
	OmsChargerStateDirectDao omsChargerStateDirectDao;
	@Resource
	OmsChargerOfflineRecordDao omsChargerOfflineRecordDao;
	@Resource
	OmsOperationSpListDao omsOperationSpListDao;
	@Resource
	OmsDeviceTypeDao omsDeviceTypeDao;
	@Autowired
	ChargerService chargerService;
	@Autowired
	SetService setService;
	@Autowired
	OmsChargerRateRepo omsChargerRateRepo;
	
	String responseMsg = "",protocol_type="",protocol_version="";
	String ev3c_frameCode;//ev3c服务器回复帧代码
	String ev3c_responseMsgHeader,ev3c_responseMsgBody,ev3c_newKeyLink,ip;
	JsonCommon<String> json = new JsonCommon<String>();
	@Override
	public JsonCommon<String> evCharLogin(Map<String, String> map) {//原 dz_login
		ip = map.get("ip");
		protocol_type = map.get("protocol_type");
		protocol_version = map.get("protocol_version");
		String data = map.get("data");
//		String port = map.get("port");
//		String chargerId = map.get("chargerId");
//		String serialNumber = map.get("serialNumber");; //流水号 20151123120442   14位   
		//ev3c 1.1 1.2 chargerId前四位 以城市区号开始，1.3开始以厂商编号后4位开始。
		switch (protocol_type){
			case "1":
				ev3c_frameCode ="A2";
			switch (protocol_version){
				case "0101":
					json = ev3c0101Login(map,data);
					break;
				case "0102":
					//信息头
					json = ev3c0102Login(map,data);
					//有信息体
					break;
				case "0103":
					//有信息头，无信息体
					json = ev3c0103Login(map,data);
					break;
				default :
					break;
			}
				break;
			default :
				break;
		}	
		return json;
	}

	private JsonCommon<String> ev3c0101Login(Map<String, String> map, String data) {
		ev3c_frameCode ="A2";
		Date now = new Date();
		String ip = map.get("ip");
		String fd = map.get("fd");
		String chargerId = map.get("chargerId");
		String cityCode =chargerId.substring(0, 4);
//		if(!cityCode.startsWith("0")){//需要检查设备地址前四位：城市代码 ,目前只判断了是否以0开始，3.0再改
//			json.setCode(OmsConstant.ErrorCodeEnum.MessageParamValueError.value());
//			json.setMsg("cityCode error");
//			return json;
//		}
		String source_ip = map.get("source_ip");
		String source_port = map.get("source_port");
		String port = map.get("port");
		String serialNumber = map.get("serialNumber");
		// 报文体 30
		String fac_login_name = data.substring(50, 58); //注册账号  00005024  厂商表中检查
		String fac_password = data.substring(58, 66); //注册密码      21968502    
		String charger_type_portNos = data.substring(66, 68); //设备一级类型  01      
//		String charger_type_portNos = data.substring(66, 68); //设备类型和充电口数量  01      
		String ev_fac_type2 = data.substring(68, 70); //设备二级类型  00     
		String ev_sn = data.substring(70, 86); //设备SN  16位                          
		String ev_gps = data.substring(86, 102); //GPS坐标   16位   00..00
		String ev_soft_version1  = data.substring(102, 106); //软件版本号  0102
//		String ev_protocol_version  = "";
//		if(data.length()<107){
//			ev_protocol_version ="0101";
//		}else{
//			 ev_protocol_version  = data.substring(106, 110);//通讯协议版本号  0102
//		}
		String communicationNo = map.get("communicationNo"); 
		String ev_serial_num = "";
		OmsFactoryList omsFactoryList;
		omsFactoryList = omsLoginDao.checkUser(fac_login_name);
		String ipStr = "00000000";
		try
		{
			ipStr = StringUtil.ip2HexStr(ip);
		}
		catch (NumberFormatException e)
		{
			log.warn(e);
		}
		ev3c_responseMsgBody = communicationNo+chargerId+"0000000000000000"+map.get("protocol_version")+
				ipStr+ "0F27"; // 端口默认:9999
				// port.substring(2, 4)+port.substring(0, 2);
		if(omsFactoryList==null){
//			FF 00 01	注册账号错误	
			json.setCode("400");
			json.setMsg("login_name error");
			log.error("login_name error");
			responseMsg = data.substring(0,8)+"FF0001"+data.substring(14,34)+ev3c_frameCode+data.substring(36,50)+ev3c_responseMsgBody;
			json.setPojo(responseMsg);
			return json;			
		}
		omsFactoryList = omsLoginDao.checkUserAndPwd(fac_login_name, fac_password);
		if(omsFactoryList==null){
//			FF 00 02	注册密码错误
			json.setCode("400");
			json.setMsg("login_name and fac_password not match");
			log.error("login_name and fac_password not match");
			responseMsg = data.substring(0,8)+"FF0002"+data.substring(14,34)+ev3c_frameCode+data.substring(36,50)+ev3c_responseMsgBody;
			json.setPojo(responseMsg);
			return json;			
		}

		//根据source_ip和source_port查询中间件服务器编号  桩硬件服务器编号  forward_srv_id
		OmsDicForwardSrvInfo omsDicForwardSrvInfo_query = new OmsDicForwardSrvInfo();
//		omsDicForwardSrvInfo_query.setMain_hardware_ip(source_ip);
//		omsDicForwardSrvInfo_query.setMain_port(Integer.valueOf(source_port));
		omsDicForwardSrvInfo_query.setMain_hardware_ip(ip);
		omsDicForwardSrvInfo_query.setMain_port_up(Integer.valueOf(port));
		OmsDicForwardSrvInfo omsDicForwardSrvInfo = omsDicForwardSrvInfoDao.findOneExample(omsDicForwardSrvInfo_query, null, null);
//		String forward_srv_id = omsDicForwardSrvInfoDao
		if(omsDicForwardSrvInfo==null){
			json.setCode("400");
			json.setMsg("ip port not exist in database");
			log.error("ip port not exist in database");
			responseMsg = data.substring(0,8)+"FFFFFF"+data.substring(14,34)+ev3c_frameCode+data.substring(36,50)+ev3c_responseMsgBody;
			json.setPojo(responseMsg);
			return json;
		}

		OmsOperationSpList omsOperMerchant_query = new OmsOperationSpList();
		omsOperMerchant_query.setCommunication_no(communicationNo);
		OmsOperationSpList omsOperMerchant = omsOperationSpListDao.findOneExample(omsOperMerchant_query, null, null);
		if(omsOperMerchant == null){
//			ev3c_responseMsgBody = communicationNo+chargerId+"0000000000000000"+map.get("protocol_version")+
//					StringUtil.ip2HexStr("111.111.111.111")+"0000";//d395ec3d
			ev3c_responseMsgHeader ="68"+StringUtil.ev3cMsgBodyBin(ev3c_responseMsgBody)+"00"+OmsConstant.MsgResponseCodeEnum.OperMerchantCodeError.value()+"0001"+chargerId+ev3c_frameCode+serialNumber;
			json.setPojo(ev3c_responseMsgHeader+ev3c_responseMsgBody);
			return json;
		}
		
		
		//chargerId 检查设备地址在不在库中		
		OmsCharger  charger_query = new OmsCharger();
		charger_query.setCharger_id(chargerId);
		OmsCharger charger = omsChargerDao.findOneExample(charger_query, null, null); 
//		if(map.get("isRegisted").equals("00")||charger==null){////未注册或者chargerId不存在，就分配个新地址chargerId
		if(map.get("isRegisted").equals("00")){////未注册，就分配个新地址chargerId
			OmsCharger chargerByCity = omsChargerDao.findOneExampleByCondition(new OmsCharger(), "where charger_id like '"+cityCode+"%' ORDER by charger_id DESC LIMIT 0,1");
			if((chargerByCity==null)||StringUtil.isBlank(chargerByCity.getCharger_id())){
				ev_serial_num = "3"+"00000000010";
				ev3c_newKeyLink = cityCode+ev_serial_num;
			}else{
				ev3c_newKeyLink =  cityCode+"3"+StringUtil.getNextCode(chargerByCity.getCharger_id().substring(5));//3代表3.0版本
			}
			//通过fac_login_name factory_id 目前设置为一样的。
			//插入电桩表，1.1、1.2为1条数据， 1.3为多条数据
			OmsCharger charger_insert = new  OmsCharger();
			charger_insert.setCharger_id(ev3c_newKeyLink);
			charger_insert.setCharger_ip(ip);
			charger_insert.setPort(Integer.valueOf(port));
			charger_insert.setPort_no(1);//1.1为单枪
			charger_insert.setFactory_id(fac_login_name);
//			charger_insert.setDev_type1(ev_fac_type1);
//			charger_insert.setDev_type2(ev_fac_type2);
			charger_insert.setSoftware_version(ev_soft_version1);
			charger_insert.setDev_sn(ev_sn);
			charger_insert.setCard_gprs(ev_gps);
			charger_insert.setCity_code(cityCode);//1.2 1.3这里不赋值
			charger_insert.setForward_srv_id(omsDicForwardSrvInfo.getForward_srv_id());
			charger_insert.setProtocol_version(protocol_version);
			charger_insert.setProtocol_type(protocol_type);
			charger_insert.setIs_parallel_charge(1);//1.X 全部是可以同时充电，因为是单枪
			charger_insert.setDevice_id("0");
			charger_insert.setCreate_time(now);
//			charger_insert.setOper_merchant_id("120161012");
			charger_insert.setOper_merchant_id(omsOperMerchant.getOper_merchant_id());
			//通过前4位charger_id来查询qr_code
			String new_qr_code = ""; // 二维码
			OmsCharger omsChargerForQrCode = omsChargerDao.findOneExampleByCondition(new OmsCharger(), " where charger_id like '" + ev3c_newKeyLink.substring(0, 4) + "%' and  LENGTH(qr_code)= 12 order by qr_code desc");
			if (omsChargerForQrCode != null) {
				String qr_code = omsChargerForQrCode.getQr_code();
				new_qr_code = qr_code.substring(0, 4) + StringUtil.complement(String.valueOf(Integer.valueOf(qr_code.substring(4)) + 1), 8);
			} else {
				new_qr_code = ev3c_newKeyLink.substring(0, 4) + "00000001";// 12位
			}
			charger_insert.setQr_code(new_qr_code);
			charger_insert.setIs_allow_open(0); // 桩是否对外开放,0:不允许 1:允许
			charger_insert.setInstallation_time(new Date()); // 安装时间
			charger_insert.setIs_allow_generate_fee(1); // 是否允许桩生成费用(0:不允许 1:允许)



			// 设置默认费率方案信息 start
			List<String> list_default_for = new ArrayList<>();
			list_default_for.add(OmsCodesConstants.DefaultSchemaType.Protocol_1.getCode());
			list_default_for.add(OmsCodesConstants.DefaultSchemaType.All.getCode());
			List<OmsChargerRateEntity> list_rate = omsChargerRateRepo.findByDefaultIndAndValidFlagAndDefaultForInOrderByDefaultForDesc(1, 1, list_default_for);
			for (OmsChargerRateEntity rate : list_rate)//费用类型:1：预约费用；2：充电费用；3：充电服务费,0为尚未分配类型的费用
			{
				if (rate.getFeeType() == 1)// 1:预约费用(默认)
					charger_insert.setRate_schema_bespeak_fee(rate.getRateSchema());
				if (rate.getFeeType() == 2)// 2:充电费用(默认)
					charger_insert.setRate_schema_charge_fee(rate.getRateSchema());
				if (rate.getFeeType() == 3)// 3:充电服务费(默认)
					charger_insert.setRate_schema_service_fee(rate.getRateSchema());
			}


			// 设置默认费率方案信息 end
			omsChargerDao.save(charger_insert);
			//插入状态表   
			//设备一级类型	1.1 1.2只是交流桩  BCD码	1		高4位：0：交流桩   1：直流桩  低4位：设备具备的充电口总数  0-n
			OmsChargerStateAlternate omsChargerStateAlternate = new OmsChargerStateAlternate();
			omsChargerStateAlternate.setCharger_id(ev3c_newKeyLink);
			omsChargerStateAlternate.setPort(Integer.valueOf(source_port));
			omsChargerStateAlternate.setPort_no(1);	
			omsChargerStateAlternate.setOnline_status(1);
			omsChargerStateAlternate.setCharge_status(0);
			omsChargerStateAlternate.setCable_status(1);
			omsChargerStateAlternate.setCharger_minute(Float.valueOf(0));
			omsChargerStateAlternate.setCharger_kwh(Float.valueOf(0));
			omsChargerStateAlternate.setValid_flag(1);
			omsChargerStateAlternate.setLast_connect_time(now);
			omsChargerStateAlternate.setLast_login_time(now);
			omsChargerStateAlternateDao.save(omsChargerStateAlternate);
			
			// 通知桩更新二维码
//			Map<String, String> qrCodeMap = new HashMap<String, String>();
//			map.put("chargerId", ev3c_newKeyLink);
//			map.put("qrCode", new_qr_code);
//			setService.setQrCode(qrCodeMap);
			
			//TODO 对时
			json.setCode("200");
			json.setMsg("register success");
			String port_str = String.valueOf(Integer.toHexString(Integer.valueOf(port)));
			ev3c_responseMsgBody = "0001"+ev3c_newKeyLink+"0000000000000000"+protocol_version+
					StringUtil.ip2HexStr("111.111.111.111")+port_str.substring(2, 4)+port_str.substring(0, 2);
//			ev3c_responseMsgBody = cityCode+ev3c_newKeyLink+"0000000000000000"+protocol_version+
//					StringUtil.ip2HexStr(source_ip)+String.valueOf(Integer.toHexString(Integer.valueOf(port)));
			String length16 = StringUtil.ev3cMsgBodyBinDivided(ev3c_responseMsgBody);
			// 修改内容:1.注册标识调整(01 -> 00), 2.新桩号修改为老桩号 start
//			ev3c_responseMsgHeader = "68"+length16+"01"+"000000"+"0001"+ev3c_newKeyLink+ev3c_frameCode+serialNumber;
			ev3c_responseMsgHeader = "68"+length16+"00"+"000000"+"0001"+chargerId+ev3c_frameCode+serialNumber;
			// 修改内容:1.注册标识调整(01 -> 00), 2.新桩号修改为老桩号 end
			//特殊处理：如果帧类型为A1且状态为未注册时，OMS需要将桩的IP和端口返回给中间件。报文+&ip=xxx.xxx.xxx.xxx&port=12345
			if(StringUtil.isBlank(fd)){
				json.setPojo(ev3c_responseMsgHeader+ev3c_responseMsgBody);
			}else{
				json.setPojo(ev3c_responseMsgHeader+ev3c_responseMsgBody+"&ip="+source_ip+"&port="+source_port+"&fd="+fd);
			}
			return json;
		}else if(charger!=null){//已注册,做更新操作
			charger.setCharger_ip(ip);
			charger.setPort(Integer.valueOf(port));
			charger.setFactory_id(fac_login_name);
//			charger.setDev_type1(ev_fac_type1);
//			charger.setDev_type2(ev_fac_type2);
			charger.setDevice_id(String.valueOf(omsDicForwardSrvInfo.getForward_srv_id()));//Fixme wrong device Id
			charger.setDev_sn(ev_sn);
			charger.setCard_gprs(ev_gps);
			charger.setCity_code(cityCode);//1.2 1.3这里不赋值
			charger.setForward_srv_id(omsDicForwardSrvInfo.getForward_srv_id());
			omsChargerDao.updateObject(charger);
			OmsChargerStateAlternate omsChargerStateAlternate_query = new OmsChargerStateAlternate();
			omsChargerStateAlternate_query.setCharger_id(chargerId);
			omsChargerStateAlternate_query.setPort_no(1);
			OmsChargerStateAlternate omsChargerStateAlternate = omsChargerStateAlternateDao.findOneExample(omsChargerStateAlternate_query, null, null);
//			omsChargerStateAlternate.setCharger_id(ev3c_newKeyLink);
			omsChargerStateAlternate.setPort(Integer.valueOf(source_port));
			omsChargerStateAlternate.setPort_no(1);	
			omsChargerStateAlternate.setOnline_status(1);
			omsChargerStateAlternate.setCharge_status(0);
			omsChargerStateAlternate.setCable_status(1);
			omsChargerStateAlternate.setCharger_minute(Float.valueOf(0));
			omsChargerStateAlternate.setCharger_kwh(Float.valueOf(0));
			omsChargerStateAlternate.setValid_flag(1);
			omsChargerStateAlternateDao.updateObject(omsChargerStateAlternate);
			json.setCode("200");
			json.setMsg(chargerId + " already registered before!");
			String port_str = String.valueOf(Integer.toHexString(Integer.valueOf(port)));
			ev3c_responseMsgBody = "0001"+chargerId+"0000000000000000"+protocol_version+
					StringUtil.ip2HexStr("111.111.111.111")+port_str.substring(2, 4)+port_str.substring(0, 2);//d395ec3d
			String length16 = StringUtil.ev3cMsgBodyBinDivided(ev3c_responseMsgBody);
			ev3c_responseMsgHeader ="68"+length16+"01"+"000000"+"0001"+chargerId+ev3c_frameCode+serialNumber;
			json.setPojo(ev3c_responseMsgHeader + ev3c_responseMsgBody);

			return json;
		}else{//设置为已注册但是桩不存在
			String port_str = String.valueOf(Integer.toHexString(Integer.valueOf(port)));
			ev3c_responseMsgBody = "0001"+chargerId+"0000000000000000"+protocol_version+
					StringUtil.ip2HexStr("111.111.111.111")+port_str.substring(2, 4)+port_str.substring(0, 2);//d395ec3d
			String length16 = StringUtil.ev3cMsgBodyBinDivided(ev3c_responseMsgBody);
			ev3c_responseMsgHeader ="68"+length16+"00"+MsgResponseCodeEnum.ChargerIdVaildNotFound.value()+"0001"+chargerId+ev3c_frameCode+serialNumber;
			json.setPojo(ev3c_responseMsgHeader+ev3c_responseMsgBody);
			return json;
			
		}
	}

	private JsonCommon<String> ev3c0102Login(Map<String, String> map, String data) {
		return ev3c0101Login(map,data);
	}

	private JsonCommon<String> ev3c0103Login(Map<String, String> map, String data) {
		String ip = map.get("ip");
		String fd = map.get("fd");
		String port = map.get("port");
		String chargerId = map.get("chargerId");
		String cityCode =chargerId.substring(0, 4);
		if(!cityCode.startsWith("0")){//需要检查设备地址前四位：城市代码 ,目前只判断了是否以0开始，3.0再改
			json.setCode("400");
			json.setMsg("cityCode error");
			return json;
		}
		String source_ip = map.get("source_ip");
		String source_port = map.get("source_port");
		//根据source_ip和source_port查询中间件服务器编号  桩硬件服务器编号  forward_srv_id
		OmsDicForwardSrvInfo omsDicForwardSrvInfo_query = new OmsDicForwardSrvInfo();
//		omsDicForwardSrvInfo_query.setMain_hardware_ip(source_ip);
//		omsDicForwardSrvInfo_query.setMain_port(Integer.valueOf(source_port));
		omsDicForwardSrvInfo_query.setMain_hardware_ip(ip);
		omsDicForwardSrvInfo_query.setMain_port_up(Integer.valueOf(port));
		OmsDicForwardSrvInfo omsDicForwardSrvInfo = omsDicForwardSrvInfoDao.findOneExample(omsDicForwardSrvInfo_query, null, null);
		String serialNumber = map.get("serialNumber");
		// 报文体 30
		String fac_login_name = data.substring(50, 58); //注册账号  00005024  厂商表中检查
		String fac_password = data.substring(58, 66); //注册密码      21968502    
		String charger_type_portNos = data.substring(66, 68); //设备类型和充电口数量  01      
		String ev_fac_type2 = data.substring(68, 70); //设备二级类型  00     
		String ev_sn = data.substring(70, 86); //设备SN  16位                          
		String ev_gps = data.substring(86, 102); //GPS坐标   16位   00..00
//		String ev_soft_version1  = data.substring(102, 106); //软件版本号  0102
//		String ev_protocol_version  = data.substring(106, 110);//通讯协议版本号  0102
		String ev_serial_num = "";
		OmsFactoryList omsFactoryList;
		omsFactoryList = omsLoginDao.checkUser(fac_login_name);
		if(omsFactoryList==null){
//			FF 00 01	注册账号错误	
			json.setCode("400");
			json.setMsg("login_name error");
			responseMsg = data.substring(0,8)+"FF0001"+data.substring(14);
			json.setPojo(responseMsg);
			return json;			
		}
		omsFactoryList = omsLoginDao.checkUserAndPwd(fac_login_name, fac_password);
		if(omsFactoryList==null){
//			FF 00 02	注册密码错误
			json.setCode("400");
			json.setMsg("login_name and fac_password not match");
			responseMsg = data.substring(0,8)+"FF0002"+data.substring(14);
			json.setPojo(responseMsg);
			return json;			
		}
		if((omsDicForwardSrvInfo==null)){
			json.setCode("400");
			json.setMsg("ip port not exist in database");
			responseMsg = data.substring(0,8)+"FF0001"+data.substring(14);
			json.setPojo(responseMsg);
			return json;	
		}	
		//chargerId 检查设备地址在不在库中		
		OmsCharger  charger_query = new OmsCharger();
		charger_query.setCharger_id(chargerId);
		OmsCharger charger = omsChargerDao.findOneExample(charger_query, null, null); 
		if(map.get("isRegisted").equals("00")||charger==null){////未注册或者chargerId不存在，就分配个新地址chargerId
			OmsCharger chargerByCity = omsChargerDao.findOneExampleByCondition(new OmsCharger(), "where charger_id like '"+cityCode+"%' ORDER by charger_id DESC LIMIT 0,1");
			if((chargerByCity==null)||StringUtil.isBlank(chargerByCity.getCharger_id())){
				ev_serial_num = "3"+"00000000010";
				ev3c_newKeyLink = cityCode+ev_serial_num;
			}else{
				ev3c_newKeyLink =  cityCode+"3"+StringUtil.getNextCode(chargerByCity.getCharger_id().substring(5));//3代表3.0版本
			}
			//通过fac_login_name factory_id 目前设置为一样的。
			//插入电桩表，1.1、1.2 为1条数据， 1.3为多条数据
			OmsCharger charger_insert = new  OmsCharger();
			charger_insert.setCharger_id(ev3c_newKeyLink);
			charger_insert.setCharger_ip(ip);
			charger_insert.setPort(Integer.valueOf(port));
			charger_insert.setPort_no(1);//1.1为单枪
			charger_insert.setFactory_id(fac_login_name);
//			charger_insert.setDev_type1(ev_fac_type1);
//			charger_insert.setDev_type2(ev_fac_type2);
			charger_insert.setDev_sn(ev_sn);
			charger_insert.setCard_gprs(ev_gps);
			charger_insert.setCity_code(cityCode);//1.2 1.3这里不赋值
	//		String forward_srv_id = omsDicForwardSrvInfoDao
			charger_insert.setForward_srv_id(omsDicForwardSrvInfo_query.getForward_srv_id());
			charger_insert.setProtocol_version(protocol_version);
			charger_insert.setProtocol_type(protocol_type);
			charger_insert.setDevice_id("0");
			omsChargerDao.save(charger_insert);
			
//			if(ev_fac_type1.endsWith("1")){//设备一级类型	BCD码	1		高4位：0：交流桩   1：直流桩   低4位：设备具备的充电口总数  0-n 
//				//应该是1到n
//				OmsCharger charger_insert = new  OmsCharger();
//				charger_insert.setCharger_id(ev3c_newKeyLink);
//				charger_insert.setCharger_ip(ip);
//				charger_insert.setPort(Integer.valueOf(port));
//				charger_insert.setFactory_id(fac_login_name);
//				charger_insert.setDev_type1(ev_fac_type1);
//				charger_insert.setDev_type2(ev_fac_type2);
//				charger_insert.setDev_sn(ev_sn);
//				charger_insert.setCard_gprs(ev_gps);
//				charger_insert.setCity_code(cityCode);//1.2 1.3这里不赋值
//		//		String forward_srv_id = omsDicForwardSrvInfoDao
//				charger_insert.setForward_srv_id(omsDicForwardSrvInfo_query.getForward_srv_id());
//				charger_insert.setProtocol_version(ev_protocol_version);
//				charger_insert.setProtocol_type(protocol_type);
//				omsChargerDao.save(charger_insert);
//			}else{
//				int n =Integer.valueOf(ev_fac_type1.substring(1, 2));
//				int i =0;
//				for(;i<n;i++){
//					OmsCharger charger_insert = new  OmsCharger();
//					charger_insert.setCharger_id(ev3c_newKeyLink);
//					charger_insert.setCharger_ip(ip);
//					charger_insert.setPort(Integer.valueOf(port));//TODO 此处为假数据
//					charger_insert.setPort_no(i+1);
//					charger_insert.setFactory_id(fac_login_name);
//					charger_insert.setDev_type1(ev_fac_type1);
//					charger_insert.setDev_type2(ev_fac_type2);
//					charger_insert.setDev_sn(ev_sn);
//					charger_insert.setCard_gprs(ev_gps);
//					charger_insert.setCity_code(cityCode);//1.2 1.3这里不赋值
//			//		String forward_srv_id = omsDicForwardSrvInfoDao
//					charger_insert.setForward_srv_id(omsDicForwardSrvInfo_query.getForward_srv_id());
//					charger_insert.setProtocol_version(ev_protocol_version);
//					charger_insert.setProtocol_type(protocol_type);
//					omsChargerDao.save(charger_insert);
//				}
//			}
			
			
			if(charger_type_portNos.startsWith("0")){//交流桩
				if(charger_type_portNos.endsWith("1")){//交流桩单口
//					OmsCharger charger_insert = new  OmsCharger();
//					charger_insert.setCharger_id(ev3c_newKeyLink);
//					charger_insert.setCharger_ip(ip);
//					charger_insert.setPort(Integer.valueOf(port));
//					charger_insert.setFactory_id(fac_login_name);
//					charger_insert.setDev_type1(ev_fac_type1);
//					charger_insert.setDev_type2(ev_fac_type2);
//					charger_insert.setDev_sn(ev_sn);
//					charger_insert.setCard_gprs(ev_gps);
//					charger_insert.setCity_code(cityCode);//1.2 1.3这里不赋值
//			//		String forward_srv_id = omsDicForwardSrvInfoDao
//					charger_insert.setForward_srv_id(omsDicForwardSrvInfo_query.getForward_srv_id());
//					charger_insert.setProtocol_version(ev_protocol_version);
//					charger_insert.setProtocol_type(protocol_type);
//					omsChargerDao.save(charger_insert);
					
					OmsChargerStateAlternate omsChargerStateAlternate = new OmsChargerStateAlternate();
					omsChargerStateAlternate.setCharger_id(ev3c_newKeyLink);
					omsChargerStateAlternate.setPort(Integer.valueOf(source_port));
					omsChargerStateAlternate.setPort_no(1);	
					omsChargerStateAlternate.setOnline_status(1);
					omsChargerStateAlternate.setCharge_status(0);
					omsChargerStateAlternate.setCable_status(1);
					omsChargerStateAlternate.setCharger_minute(Float.valueOf(0));
					omsChargerStateAlternate.setCharger_kwh(Float.valueOf(0));
					omsChargerStateAlternate.setValid_flag(1);
					Date now = new Date();
					omsChargerStateAlternate.setLast_connect_time(now);
					omsChargerStateAlternate.setLast_login_time(now);
					omsChargerStateAlternateDao.save(omsChargerStateAlternate);	
				}else{//交流桩多口
					int n =Integer.valueOf(charger_type_portNos.substring(1, 2));
					int i =0;
					for(;i<n;i++){
//						
//						OmsCharger charger_insert = new  OmsCharger();
//						charger_insert.setCharger_id(ev3c_newKeyLink);
//						charger_insert.setCharger_ip(ip);
//						charger_insert.setPort(Integer.valueOf(port));//TODO 此处为假数据
//						charger_insert.setPort_no(i+1);
//						charger_insert.setFactory_id(fac_login_name);
//						charger_insert.setDev_type1(ev_fac_type1);
//						charger_insert.setDev_type2(ev_fac_type2);
//						charger_insert.setDev_sn(ev_sn);
//						charger_insert.setCard_gprs(ev_gps);
//						charger_insert.setCity_code(cityCode);//1.2 1.3这里不赋值
//				//		String forward_srv_id = omsDicForwardSrvInfoDao
//						charger_insert.setForward_srv_id(omsDicForwardSrvInfo_query.getForward_srv_id());
//						charger_insert.setProtocol_version(ev_protocol_version);
//						charger_insert.setProtocol_type(protocol_type);
//						omsChargerDao.save(charger_insert);
						
						OmsChargerStateAlternate omsChargerStateAlternate = new OmsChargerStateAlternate();
						omsChargerStateAlternate.setCharger_id(ev3c_newKeyLink);
						omsChargerStateAlternate.setPort(Integer.valueOf(source_port));//TODO 此处为假数据
						omsChargerStateAlternate.setPort_no(i+1);	
						omsChargerStateAlternate.setOnline_status(1);
						omsChargerStateAlternate.setCharge_status(0);
						omsChargerStateAlternate.setCable_status(1);
						omsChargerStateAlternate.setCharger_minute(Float.valueOf(0));
						omsChargerStateAlternate.setCharger_kwh(Float.valueOf(0));
						omsChargerStateAlternate.setValid_flag(1);
						Date now = new Date();
						omsChargerStateAlternate.setLast_connect_time(now);
						omsChargerStateAlternate.setLast_login_time(now);
						omsChargerStateAlternateDao.save(omsChargerStateAlternate);	
					}
				}
			}else{//直流桩
				if(charger_type_portNos.endsWith("1")){//直流桩单口
//					OmsCharger charger_insert = new  OmsCharger();
//					charger_insert.setCharger_id(ev3c_newKeyLink);
//					charger_insert.setCharger_ip(ip);
//					charger_insert.setPort(Integer.valueOf(port));
//					charger_insert.setFactory_id(fac_login_name);
//					charger_insert.setDev_type1(ev_fac_type1);
//					charger_insert.setDev_type2(ev_fac_type2);
//					charger_insert.setDev_sn(ev_sn);
//					charger_insert.setCard_gprs(ev_gps);
//					charger_insert.setCity_code(cityCode);//1.2 1.3这里不赋值
////					charger_insert.setSerial_no(ev_serial_num);
//			//		String forward_srv_id = omsDicForwardSrvInfoDao
//					charger_insert.setForward_srv_id(omsDicForwardSrvInfo_query.getForward_srv_id());
//					charger_insert.setProtocol_version(ev_protocol_version);
//					charger_insert.setProtocol_type(protocol_type);
//					omsChargerDao.save(charger_insert);
					
					OmsChargerStateDirect omsChargerStateDirect = new OmsChargerStateDirect();
					omsChargerStateDirect.setCharger_id(ev3c_newKeyLink);
					omsChargerStateDirect.setPort(Integer.valueOf(source_port));
					omsChargerStateDirect.setPort_no(1);	
					omsChargerStateDirect.setOnline_status(1);
					omsChargerStateDirect.setCharge_status(0);
					omsChargerStateDirect.setCable_status(1);
					omsChargerStateDirect.setCharger_minute(Float.valueOf(0));
					omsChargerStateDirect.setCharger_kwh(Float.valueOf(0));
					omsChargerStateDirect.setValid_flag(1);
					Date now = new Date();
					omsChargerStateDirect.setLast_connect_time(now);
					omsChargerStateDirect.setLast_login_time(now);
					omsChargerStateDirectDao.save(omsChargerStateDirect);	
				}else{//直流桩多口
					int n =Integer.valueOf(charger_type_portNos.substring(1, 2));
					int i =0;
					for(;i<n;i++){
//						OmsCharger charger_insert = new  OmsCharger();
//						charger_insert.setCharger_id(ev3c_newKeyLink);
//						charger_insert.setCharger_ip(ip);
//						charger_insert.setPort(Integer.valueOf(port));//TODO 此处为假数据
//						charger_insert.setPort_no(i+1);
//						charger_insert.setFactory_id(fac_login_name);
//						charger_insert.setDev_type1(ev_fac_type1);
//						charger_insert.setDev_type2(ev_fac_type2);
//						charger_insert.setDev_sn(ev_sn);
//						charger_insert.setCard_gprs(ev_gps);
//						charger_insert.setCity_code(cityCode);//1.2 1.3这里不赋值
//				//		String forward_srv_id = omsDicForwardSrvInfoDao
//						charger_insert.setForward_srv_id(omsDicForwardSrvInfo_query.getForward_srv_id());
//						charger_insert.setProtocol_version(ev_protocol_version);
//						charger_insert.setProtocol_type(protocol_type);
//						omsChargerDao.save(charger_insert);
						
						OmsChargerStateDirect omsChargerStateDirect = new OmsChargerStateDirect();
						omsChargerStateDirect.setCharger_id(ev3c_newKeyLink);
						omsChargerStateDirect.setPort(Integer.valueOf(source_port));
						omsChargerStateDirect.setPort_no(i+1);	
						omsChargerStateDirect.setOnline_status(1);
						omsChargerStateDirect.setCharge_status(0);
						omsChargerStateDirect.setCable_status(1);
						omsChargerStateDirect.setCharger_minute(Float.valueOf(0));
						omsChargerStateDirect.setCharger_kwh(Float.valueOf(0));
						omsChargerStateDirect.setValid_flag(1);
						Date now = new Date();
						omsChargerStateDirect.setLast_connect_time(now);
						omsChargerStateDirect.setLast_login_time(now);
						omsChargerStateDirectDao.save(omsChargerStateDirect);	
					}
				}
			}
			//TODO 对时
			json.setCode("200");
			json.setMsg("register success");
//			String port_str = String.valueOf(Integer.toHexString(Integer.valueOf(port)));
			String update_ip ="111.112.113.114";
			String update_port ="1234";
			ev3c_responseMsgBody = "0001"+ev3c_newKeyLink+"0000000000000000"+protocol_version+
					StringUtil.ip2HexStr(update_ip)+update_port.substring(2, 4)+update_port.substring(0, 2)+Integer.toHexString(60).toString()+Integer.toHexString(60).toString()+"05";
//			ev3c_responseMsgBody = cityCode+ev3c_newKeyLink+"0000000000000000"+protocol_version+
//					StringUtil.ip2HexStr(source_ip)+String.valueOf(Integer.toHexString(Integer.valueOf(port)));
			String  length16 = Integer.toHexString(ev3c_responseMsgBody.length());
			if(length16.length()==1){
				length16 = "0"+length16+"00";
			}else if(length16.length()==2){
				length16 =  length16+"00";
			}
			ev3c_responseMsgHeader = "68"+length16+"01"+"000000"+"0001"+ev3c_newKeyLink+ev3c_frameCode+serialNumber;
			if(StringUtil.isBlank(fd)){
				json.setPojo(ev3c_responseMsgHeader+ev3c_responseMsgBody);
			}else{
				json.setPojo(ev3c_responseMsgHeader+ev3c_responseMsgBody+"&ip="+source_ip+"&port="+source_port+"&fd="+fd);
			}
			return json;
		}else{//已注册,做更新操作
			charger.setCharger_id(chargerId);
			charger.setCharger_ip(ip);
			charger.setPort(Integer.valueOf(port));
			charger.setFactory_id(fac_login_name);
//			charger.setDev_type1(ev_fac_type1);
//			charger.setDev_type2(ev_fac_type2);
			charger.setDev_sn(ev_sn);
			charger.setCard_gprs(ev_gps);
			charger.setCity_code(cityCode);//1.2 1.3这里不赋值
			charger.setForward_srv_id(omsDicForwardSrvInfo.getForward_srv_id());
			omsChargerDao.updateObject(charger);
			OmsChargerStateAlternate omsChargerStateAlternate_query = new OmsChargerStateAlternate();
			omsChargerStateAlternate_query.setCharger_id(chargerId);
			omsChargerStateAlternate_query.setPort_no(1);
			OmsChargerStateAlternate omsChargerStateAlternate = omsChargerStateAlternateDao.findOneExample(omsChargerStateAlternate_query, null, null);
			omsChargerStateAlternate.setCharger_id(chargerId);
			omsChargerStateAlternate.setPort(Integer.valueOf(source_port));
			omsChargerStateAlternate.setOnline_status(1);
			omsChargerStateAlternate.setCharge_status(0);
			omsChargerStateAlternate.setCable_status(1);
			omsChargerStateAlternate.setCharger_minute(Float.valueOf(0));
			omsChargerStateAlternate.setCharger_kwh(Float.valueOf(0));
			omsChargerStateAlternate.setValid_flag(1);
			omsChargerStateAlternateDao.updateObject(omsChargerStateAlternate);
			json.setCode("200");
			json.setMsg(chargerId+" already registered before!");
			String update_ip ="111.112.113.114";
			String update_port ="1234";
//			String port_str = String.valueOf(Integer.toHexString(Integer.valueOf(port)));
			ev3c_responseMsgBody = "0001"+chargerId+"0000000000000000"+protocol_version+
					StringUtil.ip2HexStr(update_ip)+update_port.substring(2, 4)+update_port.substring(0, 2);//d395ec3d
			String  length16 = Integer.toHexString(ev3c_responseMsgBody.length());
			if(length16.length()==1){
				length16 = "0"+length16+"00";
			}else if(length16.length()==2){
				length16 =  length16+"00";
			}
			ev3c_responseMsgHeader ="68"+length16+"01"+"000000"+"0001"+chargerId+ev3c_frameCode+serialNumber;
			json.setPojo(ev3c_responseMsgHeader+ev3c_responseMsgBody);
			return json;
		}
	}

	@Override
	public JsonCommon<String> dzLoginOut(Map<String, String> map) {
		JsonCommon<String> json = new JsonCommon<String>();
		protocol_type = map.get("protocol_type");
		protocol_version = map.get("protocol_version");
		String data = map.get("data");
		switch (protocol_type){
			case "1":
				ev3c_frameCode ="A4";
				switch (protocol_version){
					case "0101":
//						ev3c0101Logout(map,data);
						json.setCode("400");
						json.setMsg("ev3c 0101 can not logout!");
						break;
					case "0102":
						//信息头
						json = ev3c0102Logout(map,data);
						//有信息体
						break;
					case "0103":
						//有信息头，无信息体
						json = ev3c0103Logout(map,data);
						break;
					default :
						break;
				}
				break;
			default :
				break;
		}
		return json;

	}

	
	private JsonCommon<String> ev3c0102Logout(Map<String, String> map, String data) {
		//OmsCharger  charger_type  1--直流  2--交流  3--混合
		//oms_charger_offline_record(下线记录表)
		//oms_charger_state_alternate[交流充电桩状态表]oms_charger_state_direct[直流充电桩状态表]
		//online_status 1代表在线  0代表离线  last_connect_time
		JsonCommon<String> json = new JsonCommon<String>();
		String chargerId = map.get("chargerId");
		String serialNumber =  map.get("serialNumber");//信任桩上的时间
		Date serialNumber_date = StringUtil.StrToDate(serialNumber);
		OmsCharger  charger_query = new OmsCharger();
		charger_query.setCharger_id(chargerId);
		OmsCharger charger = omsChargerDao.findOneExample(charger_query, null, null); 
		if(charger==null){
			json.setCode("10301201");//查询不到桩
			json.setMsg("chargerId :"+chargerId+" can not find ");
			responseMsg = data.substring(0,8)+"FFFFFF"+data.substring(14,34)+ev3c_frameCode+data.substring(36);
			json.setPojo(responseMsg);
			return json;
		}
		OmsChargerOfflineRecord omsChargerOfflineRecord = new OmsChargerOfflineRecord();
		omsChargerOfflineRecord.setCharger_id(chargerId);
		omsChargerOfflineRecord.setDetection_time(serialNumber_date);
		omsChargerOfflineRecordDao.save(omsChargerOfflineRecord);
//		charger_query.setCharger_id(chargerId);
//		List<OmsCharger> chargerList = omsChargerDao.findExample(charger_query, null, null, null, null);
		OmsChargerStateAlternate alternate_query = new OmsChargerStateAlternate();
		alternate_query.setCharger_id(chargerId);
		List<OmsChargerStateAlternate> alternateList = omsChargerStateAlternateDao.findExample(alternate_query, null, null, null, null);
		if(alternateList.size()>0){//交流
			for(OmsChargerStateAlternate alternate:alternateList){
				alternate.setOnline_status(0);
				alternate.setLast_connect_time(serialNumber_date);
				omsChargerStateAlternateDao.updateObject(alternate);
			}
		}else{//直流
			OmsChargerStateDirect direct_query = new OmsChargerStateDirect();
			List<OmsChargerStateDirect> directList = omsChargerStateDirectDao.findExample(direct_query, null, null, null, null);
			for(OmsChargerStateDirect direct:directList){
				direct.setOnline_status(0);
				direct.setLast_connect_time(serialNumber_date);
				omsChargerStateDirectDao.updateObject(direct);
			}
		}
		json.setCode("200");
		json.setMsg("chargerId :"+chargerId+" logout success");
		responseMsg = data.substring(0, 34)+ev3c_frameCode+data.substring(36);
		json.setPojo(responseMsg);
		return json;
	}
	
	private JsonCommon<String> ev3c0103Logout(Map<String, String> map, String data) {
		return ev3c0102Logout(map, data);
	}

	@Override
	public Map<String, String> ev3c02chargerRegister(Map<String, String> map) throws OmsDaoException
	{

		log.info("Charger register");
		log.info(map);
		String ip = map.get("ip");
		String port = map.get("port");
		String chargerId = map.get("chargerId");
		String fac_code = chargerId.substring(0, 4);
		String source_ip = map.get("source_ip");
		String source_port = map.get("source_port");

		String chargerType = map.get("chargerType");//// 0：交流桩   1：直流桩  F：其它

		int charger_type_indb = 0;
		if (OmsConstant.ChargerType.AC.equals(chargerType))
			charger_type_indb = 2;
		else if(OmsConstant.ChargerType.DC.equals(chargerType))
			charger_type_indb = 1;

		String fac_login_name = map.get("fac_login_name");
		String fac_password = map.get("fac_password");
		String port_quantity = map.get("port_quantity");
		String is_parallel_charge = map.get("is_parallel_charge");
		String ev_fac_type1 = map.get("ev_fac_type1");
		String ev_fac_type2 = map.get("ev_fac_type2");
		String software_version = map.get("software_version");
		String ev_sn = map.get("ev_sn");

		String sn_ascii = SNUtils.convertToAsciiDesc(ev_sn);

		String protocol_version = map.get("protocol_version");
		String protocol_type = map.get("protocol_type");

		String serialNumber = map.get("serialNumber");
		String ev_serial_num = "";//生成桩号的流水号

		//pengyu add 20170811
		//根据source_ip和source_port查询中间件服务器编号  桩硬件服务器编号  forward_srv_id
		OmsDicForwardSrvInfo omsDicForwardSrvInfo_query = new OmsDicForwardSrvInfo();
//		omsDicForwardSrvInfo_query.setMain_hardware_ip(source_ip);
//		omsDicForwardSrvInfo_query.setMain_port(Integer.valueOf(source_port));
		omsDicForwardSrvInfo_query.setMain_hardware_ip(ip);
		omsDicForwardSrvInfo_query.setMain_port_up(Integer.valueOf(port));
		OmsDicForwardSrvInfo omsDicForwardSrvInfo = omsDicForwardSrvInfoDao.findOneExample(omsDicForwardSrvInfo_query, null, null);
//		String forward_srv_id = omsDicForwardSrvInfoDao
//		if(omsDicForwardSrvInfo==null){
//			json.setCode("400");
//			json.setMsg("ip port not exist in database");
//			log.error("ip port not exist in database");
//			map.put("msgResponseCode","FFFFFF");//此IP和端口对应的中间件服务不存在
//			return map;
//		}
		
		
		log.info("find charger");
		OmsFactoryList omsFactoryList;
		omsFactoryList = omsLoginDao.checkFactory(chargerId.substring(0, 4));
		if (omsFactoryList == null)
		{
			//			FF 00 01	注册账号错误
			log.error("chargerId.substring(0, 4) error ");
			json.setCode("400");
			json.setMsg("factoy code in chargerId error");
			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.AccountError.value());//"FF0001"
			return map;
		}
		omsFactoryList = omsLoginDao.checkUser(fac_login_name);
		if (omsFactoryList == null)
		{
			//			FF 00 01	注册账号错误
			log.error("account error");
			json.setCode("400");
			json.setMsg("login_name error");
			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.AccountError.value());//"FF0001"
			return map;
		}
		log.info("account accept");

		omsFactoryList = omsLoginDao.checkUserAndPwd(fac_login_name, fac_password);
		if (omsFactoryList == null)
		{
			log.error("password wrong");
			//			FF 00 02	注册密码错误
			json.setCode("400");
			json.setMsg("login_name and fac_password not match");
			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.PwdError.value());//"FF0002"
			return map;
		}
		log.info("login ok");

		String communicationNo = map.get("communicationNo");
		log.info("=============================== " + communicationNo);
		OmsOperationSpList omsOperMerchant_query = new OmsOperationSpList();
		omsOperMerchant_query.setCommunication_no(communicationNo);
		OmsOperationSpList omsOperMerchant = omsOperationSpListDao.findOneExample(omsOperMerchant_query, null, null);
		if (omsOperMerchant == null)
		{
			log.error("Merchant not found");
			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.OperMerchantCodeError.value());
			return map;
		}
		log.info("Merchant found");

		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(*) cnt FROM oms_charger c ");
		sql.append(" INNER JOIN oms_device_type d ON c.device_id = d.device_id ");
		sql.append(" WHERE c.valid_flag = 1 AND d.valid_flag = 1 ");
		sql.append(" AND c.dev_sn = '%1$s' AND d.dev_type1 = '%2$s' AND d.dev_type2 = '%3$s' AND d.factory_id = '%4$s' ");


		List<Map<String, Object>> query = omsChargerDao.findDataBySql(String.format(sql.toString(), ev_sn, ev_fac_type1, ev_fac_type2, omsFactoryList.getFactory_id()));
		if (query != null && !query.isEmpty() && (Long)query.get(0).get("cnt") > 0)
		{
			log.error(String.format("charger S/N is exist in DB, can not assign new id to it, S/N: %1$s, type1: %2$s, type2: %3$s", ev_sn, ev_fac_type1, ev_fac_type2));
			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.ChargerIdDuplicationError.value());
			return map;
		}
		log.info("S/N is new");

		OmsDeviceType deviceType_query = new OmsDeviceType();
		deviceType_query.setFactory_id(omsFactoryList.getFactory_id());
		deviceType_query.setDev_type1(ev_fac_type1);
		deviceType_query.setDev_type2(ev_fac_type2);
		deviceType_query.setValid_flag(1);//需要设备是有效的
		OmsDeviceType deviceType = omsDeviceTypeDao.findOneExample(deviceType_query, null, null);
		if(deviceType == null)
		{
			log.error(String.format("Cannot find an factory_id, dev type 1, dev type 2 in db, factory_id: %1$s, type1: %2$s, type2: %3$s", omsFactoryList.getFactory_id(), ev_fac_type1, ev_fac_type2));
			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.DeviceTypeNotFound.value());
			return map;
		}
		log.info("found device type");

		String device_id = deviceType.getDevice_id();

		log.info("look for faccode");
		String new_chargerId = null;

		OmsCharger chargerByFacCode = omsChargerDao.findOneExampleByCondition(new OmsCharger(), "where charger_id like '" + fac_code + "%' ORDER by charger_id DESC LIMIT 0,1");
		if ((chargerByFacCode == null) || StringUtil.isBlank(chargerByFacCode.getCharger_id()))
		{
			ev_serial_num = "3" + "00000000010";
			new_chargerId = fac_code + ev_serial_num;
		}
		else
		{
			new_chargerId = fac_code + "3" + StringUtil.getNextCode(chargerByFacCode.getCharger_id().substring(5));//3代表3.0版本
		}
		log.info(new_chargerId);

		Date now = new Date();

		map.put("chargerId", new_chargerId);
		//		Date now = new Date();
		//桩表插入一条数据

		log.info("insert to db");

		OmsCharger charger_insert = new OmsCharger();
		charger_insert.setCharger_id(new_chargerId);
		charger_insert.setCharger_ip(source_ip);
		charger_insert.setPort(Integer.valueOf(source_port));
		charger_insert.setPort_quantity(1);
		charger_insert.setIs_parallel_charge(Integer.valueOf(is_parallel_charge));
		charger_insert.setFactory_id(omsFactoryList.getFactory_id());
		//		charger_insert.setDev_type1(ev_fac_type1);
		//		charger_insert.setDev_type2(ev_fac_type2);
		charger_insert.setDev_sn(ev_sn);
		//		String forward_srv_id = omsDicForwardSrvInfoDao
				charger_insert.setForward_srv_id(omsDicForwardSrvInfo!=null?omsDicForwardSrvInfo.getForward_srv_id():4);//默认为4
		charger_insert.setIs_allow_open(1);
		charger_insert.setSoftware_version(software_version);
		charger_insert.setProtocol_version(protocol_version);
		charger_insert.setProtocol_type(protocol_type);
		charger_insert.setCreate_time(now);
		charger_insert.setUpdate_time(now);
		charger_insert.setValid_flag(1);
		charger_insert.setCreate_oper_id("oms");
		charger_insert.setUpdate_oper_id("oms");
		charger_insert.setDevice_id(device_id);
		charger_insert.setCharger_type(charger_type_indb);
		charger_insert.setOper_merchant_id(omsOperMerchant.getOper_merchant_id());


		// 设置默认费率方案信息 start
		List<String> list_default_for = new ArrayList<>();
		list_default_for.add(OmsCodesConstants.DefaultSchemaType.Protocol_2.getCode());
		list_default_for.add(OmsCodesConstants.DefaultSchemaType.All.getCode());
		List<OmsChargerRateEntity> list_rate = omsChargerRateRepo.findByDefaultIndAndValidFlagAndDefaultForInOrderByDefaultForDesc(1, 1, list_default_for);
		for (OmsChargerRateEntity rate : list_rate)//费用类型:1：预约费用；2：充电费用；3：充电服务费,0为尚未分配类型的费用
		{
			if (rate.getFeeType() == 1)// 1:预约费用(默认)
				charger_insert.setRate_schema_bespeak_fee(rate.getRateSchema());
			if (rate.getFeeType() == 2)// 2:充电费用(默认)
				charger_insert.setRate_schema_charge_fee(rate.getRateSchema());
			if (rate.getFeeType() == 3)// 3:充电服务费(默认)
				charger_insert.setRate_schema_service_fee(rate.getRateSchema());
		}

		charger_insert.setIs_allow_generate_fee(1); // 是否允许桩生成费用(0:不允许 1:允许)
		// 设置默认费率方案信息 end
		omsChargerDao.save(charger_insert);
		log.info("charger record insert to db");


		log.info(chargerType);
		switch (chargerType)
		{// 0：交流桩   1：直流桩  F：其它
			case OmsConstant.ChargerType.AC://0：交流桩
				log.info("AC");
				//			port_quantity  枪口数量
				for (int i = 0; i < Integer.valueOf(port_quantity); i++)
				{
					OmsChargerStateAlternate state = new OmsChargerStateAlternate();
					state.setCharger_id(new_chargerId);
					state.setPort(Integer.valueOf(source_port));
					state.setPort_no(i + 1);//2.0的端口序号从1开始
					state.setOnline_status(0);//1代表在线  0代表离线
					state.setCharge_status(0);//0: 空闲;1: 预约;2 充电; 3 故障;4:占用中 8:离线
					state.setCable_status(1);
					state.setCharger_minute(Float.valueOf(0));
					state.setCharger_kwh(0f);
					state.setValid_flag(1);
					//				omsChargerStateAlternate.setLast_connect_time(now);
					//				omsChargerStateAlternate.setLast_login_time(now);
					omsChargerStateAlternateDao.save(state);

				}
				break;
			case OmsConstant.ChargerType.DC://1：直流桩
				for (int i = 0; i < Integer.valueOf(port_quantity); i++)
				{
					OmsChargerStateDirect state = new OmsChargerStateDirect();
					state.setCharger_id(new_chargerId);
					state.setPort(Integer.valueOf(source_port));
					state.setPort_no(i + 1);//2.0的端口序号从1开始
					state.setOnline_status(0);//1代表在线  0代表离线
					state.setCharge_status(0);//0: 空闲;1: 预约;2 充电; 3 故障;4:占用中 8:离线
					state.setCable_status(1);
					state.setCharger_minute(Float.valueOf(0));
					state.setCharger_kwh(0f);
					state.setValid_flag(1);
					//			omsChargerStateAlternate.setLast_connect_time(now);
					//			omsChargerStateAlternate.setLast_login_time(now);
					omsChargerStateDirectDao.save(state);
				}
				log.info("DC");
				break;
			default:
				map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.SysError.value());
				return map;
		}
		map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.Normal.value());
		log.info(map);
		return map;
	}

	@Override
	public Map<String, String> ev3c02chargerUnRegister(Map<String, String> map) {
//		map = getEv3c2MsgHeaderByMiddleBegin(map);
//		// 报文体解析
//		String chargerId = map.get("chargerId");
//		String chargerMsgBody = chargerId;
//		String unregister_reason = chargerMsgBody.substring(0, 2); //注销原因		
//		map.put("unregister_reason", unregister_reason);	
		String chargerId = map.get("chargerId");
		String chargerType = map.get("chargerType");//// 0：交流桩   1：直流桩  F：其它
		//有效标志置为0，状态置为离线
		OmsCharger charger_query = new OmsCharger();
		charger_query.setCharger_id(chargerId);
		OmsCharger charger = omsChargerDao.findOneExample(charger_query, null, null);
		if(charger!=null)
		{
			omsChargerDao.LogicDeleteObject(charger);
			switch (charger.getCharger_type())
			{// 2：交流桩   1：直流桩  F：其它
				case 2://2：交流桩
					omsChargerStateAlternateDao.exec("update oms_charger_state_alternate set online_status = 0  where charger_id ='" + chargerId + "'");
					break;
				case 1://1：直流桩
					omsChargerStateDirectDao.exec("update oms_charger_state_direct set online_status = 0 where charger_id ='" + chargerId + "'");
					break;
				default:
					map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.SysError.value());
					return map;
			}
		}
		map.put("msgResponseCode",OmsConstant.MsgResponseCodeEnum.Normal.value());
		return map;
	}

	@Override
	public void ev3c02chargerLogin(Map<String, String> map) throws BizException
	{
		//		//报文头解析
		//				map = getEv3c2MsgHeaderByMiddleBegin(map);
		//				// 报文体解析
		//				String chargerMsgBody = map.get("chargerMsgBody");
		//				String fac_login_name = chargerMsgBody.substring(0, 8); //注册账号  00005024  厂商表中检查
		//				String fac_password = chargerMsgBody.substring(8, 16); //注册密码      21968502
		//				String coordinate_x =  chargerMsgBody.substring(16, 24); //*GPS经度	BIN码
		//				String coordinate_y =  chargerMsgBody.substring(24, 32); //*GPS纬度	BIN码
		//				String software_version =  chargerMsgBody.substring(24, 32); //*GPS纬度	BIN码
		//				String protocol_version = map.get("protocol_version"); //*GPS纬度	BIN码
		//				map.put("fac_login_name", fac_login_name);
		//				map.put("fac_password", fac_password);
		//				map.put("software_version", software_version);
		//				map.put("protocol_version", protocol_version);
		//				return map;

		log.info("Charger login");
		String ip = map.get("ip");
		//String fd = map.get("fd");
		String port = map.get("port");
		String chargerId = map.get("chargerId");
		//		String fac_code =chargerId.substring(0, 4);
		//		String source_ip = map.get("source_ip");
		//		String source_port = map.get("source_port");

		//		String chargerType = map.get("chargerType");//// 0：交流桩   1：直流桩  F：其它

		String fac_login_name = map.get("fac_login_name");
		String fac_password = map.get("fac_password");
		log.info(map);
		//验证用户名密码
		OmsFactoryList omsFactoryList;
		omsFactoryList = omsLoginDao.checkUser(fac_login_name);
		if (omsFactoryList == null)
		{
			//			FF 00 01	注册账号错误
			//			json.setCode("400");
			//			json.setMsg("login_name error");
			log.error("Login name undefined");
			throw new BizException(OmsConstant.MsgResponseCodeEnum.AccountError.value(), "Login name undefined");
//			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.AccountError.value());//"FF0001"
//			return map;
		}
		log.info("account ok");
		omsFactoryList = omsLoginDao.checkUserAndPwd(fac_login_name, fac_password);
		if (omsFactoryList == null)
		{
			//			FF 00 02	注册密码错误
			//			json.setCode("400");
			//			json.setMsg("login_name and fac_password not match");
			log.error("login name and password does not match");
			throw new BizException(OmsConstant.MsgResponseCodeEnum.PwdError.value(), "login name and password does not match");
//			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.PwdError.value());//"FF0001"
//			return map;
		}
		log.info("login ok");
		//验证桩地址 并且valid_flag =1 
		OmsCharger charger_query = new OmsCharger();
		charger_query.setValid_flag(1);
		charger_query.setCharger_id(chargerId);
		OmsCharger charger = omsChargerDao.findOneExample(charger_query, null, null);
		if (charger == null)
		{
			//			json.setCode("400");
			//			json.setMsg("charger not found");
			log.error("charger not found");
			throw new ChargerNotFoundException(OmsConstant.MsgResponseCodeEnum.ChargerIdVaildNotFound.value(), "charger not found");
//			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.ChargerIdVaildNotFound.value());//"FF0303"
//			return map;
		}
		log.info("charger found");

		OmsDicForwardSrvInfo fwd_srv_query = new OmsDicForwardSrvInfo();
		fwd_srv_query.setValid_flag(1);
		log.info(ip);
		log.info(port);
		//		ip = "192.168.5.208";
		//		port = "8291";
		fwd_srv_query.setMain_hardware_ip(ip);
		fwd_srv_query.setMain_port_up(Integer.valueOf(port));
		OmsDicForwardSrvInfo serverinfo = omsDicForwardSrvInfoDao.findOneExample(fwd_srv_query, null, null);
		if (serverinfo == null)
		{
			log.error("cannot find corresponding forword server for particular charger");
			throw new FwdServerNotFoundException(OmsConstant.MsgResponseCodeEnum.SysError.value(), "cannot find corresponding forword server for particular charger");
//			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.SysError.value());//"FFFFFF"
//			return map;
		}
		log.info("server found");

		charger.setForward_srv_id(serverinfo.getForward_srv_id());
		charger.setProtocol_type(map.get("protocol_type"));
		charger.setProtocol_version(map.get("protocol_version"));

		if(StringUtils.isEmpty(charger.getQr_code()))
		{
			String qrCode = chargerService.updateQrCode(chargerId);
			charger.setQr_code(qrCode);
			try
			{
				// 通知桩更新二维码
				Map<String, String> m = new HashMap<String, String>();
				m.put("chargerId", chargerId);
				m.put("qrCode", qrCode);
				setService.setQrCode(m);
			}
			catch (CreateConnectionFailException | RetryFailException e)
			{
				log.error(e.getMessage(), e);
			}
		}

		omsChargerDao.updateObject(charger);
		log.info("db update ok");

		//修改后，上线时保持之前的状态 pengyu modify 20170105. 由于2.0的桩可以保持之前的状态
		switch (charger.getCharger_type())
		{// 2：交流桩   1：直流桩
			case 2://0：交流桩
//				omsChargerStateAlternateDao.exec("update oms_charger_state_alternate set online_status = 1,charge_status = 0  where charger_id ='" + chargerId + "'");
				omsChargerStateAlternateDao.exec("update oms_charger_state_alternate set online_status = 1  where charger_id ='" + chargerId + "'");

				break;
			case 1://1：直流桩
//				omsChargerStateDirectDao.exec("update oms_charger_state_direct set online_status = 1,charge_status = 0  where charger_id ='" + chargerId + "'");
				omsChargerStateDirectDao.exec("update oms_charger_state_direct set online_status = 1  where charger_id ='" + chargerId + "'");
				break;
			default:
				throw new BizException(OmsConstant.MsgResponseCodeEnum.SysError.value(), "invalid charger type");
//				return map;
		}

		log.info("After login process");
//		return map;
	}

	@Override
	public Map<String, String> ev3c02chargerLogout(Map<String, String> map) {
		//把桩的状态置为离线，同时往下线表中加入一条数据即可
		JsonCommon<String> json = new JsonCommon<String>();
		String chargerId = map.get("chargerId");
		String chargerType = map.get("chargerType");// 0：交流桩   1：直流桩  F：其它
		String chargerSerialNumber =  map.get("chargerSerialNumber");//不信任桩上的时间，暂时不用这个字段
//		Date serialNumber_date = StringUtil.StrToDate(chargerSerialNumber);
		OmsCharger  charger_query = new OmsCharger();
		charger_query.setCharger_id(chargerId);
		OmsCharger charger = omsChargerDao.findOneExample(charger_query, null, null); 
		if(charger==null){
			json.setCode("10301201");//查询不到桩
			json.setMsg("chargerId :"+chargerId+" can not find ");
			map.put("msgResponseCode",OmsConstant.MsgResponseCodeEnum.ChargerIdVaildNotFound.value());
			return map;
		}
		OmsChargerOfflineRecord omsChargerOfflineRecord = new OmsChargerOfflineRecord();
		omsChargerOfflineRecord.setCharger_id(chargerId);
		omsChargerOfflineRecord.setDetection_time(new Date());
		omsChargerOfflineRecordDao.save(omsChargerOfflineRecord);
		switch(chargerType){// 0：交流桩   1：直流桩  F：其它
		case "0"://0：交流桩
			omsChargerStateAlternateDao.exec("update oms_charger_state_alternate set online_status = 0  where charger_id ='"+chargerId+"'");
			break;
		case "1"://1：直流桩
			omsChargerStateDirectDao.save("update oms_charger_state_direct set online_status = 0  where charger_id ='"+chargerId+"'");	
		default:
			map.put("msgResponseCode",OmsConstant.MsgResponseCodeEnum.SysError.value());
			return map;
		}
		map.put("msgResponseCode",OmsConstant.MsgResponseCodeEnum.Normal.value());
		return map;
	}

}
